import { FC, useState } from "react";
import { View, Image, ImageProps } from "@tarojs/components";
import Loading from "../../images/loading.gif";
import classNames from "classnames";
import "./style.scss";
// export type ModeTypes =
//   | "scaleToFill"
//   | "aspectFit"
//   | "aspectFill"
//   | "widthFix"
//   | "heightFix"
//   | "top"
//   | "bottom"
//   | "center"
//   | "left";

export interface ImageViewProps {
  width?: string;
  height?: string;
  src: string;
  // mode?: ModeTypes;
  lazy?: boolean;
  round?: boolean;
  onClick?: () => void;
}
// lazyLoad
// 联合类型
export type ImageItemProps = ImageProps & ImageViewProps;

export const ImageView: FC<ImageItemProps> = (props) => {
  const [error, setError] = useState(false);
  const [loading, setLoading] = useState(true);

  const { width, height, src, mode, lazy = true, round, onClick } = props;
  const classes = classNames("image", {
    ["round"]: round,
  });
  const onError = () => {
    setError(true);
  };
  const onLoad = () => {
    setLoading(false);
  };

  return (
    <View className={"image-view"} onClick={onClick} style={{ width, height }}>
      {error || loading ? (
        <Image
          mode={mode}
          lazyLoad={lazy}
          src={Loading}
          style={{ width, height }}
          className={classes}
          onError={onError}
          onLoad={onLoad}
        />
      ) : (
        <Image
          mode={mode}
          lazyLoad={lazy}
          src={src}
          style={{ width, height }}
          className={classes}
          onError={onError}
          onLoad={onLoad}
        />
      )}
    </View>
  );
};

ImageView.defaultProps = {
  width: "100px",
  height: "100px",
  mode: "scaleToFill",
  // src: "",
};

export default ImageView;
